package de.dailab.prefgen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.dailab.prefgen.ObjectAnnotations.ValueDescription;


public class DefaultNameMapper implements INameMapping {

	@Override
	public String toHumanReadable(Method m, Object superObject, TYPE type) {

		switch (type) {
		case KEY:
			return m.getDeclaringClass().getName()+ "." + m.getName();
		case NAME:
			return Utils.splitCamalCase(Utils.stripPrefix(m.getName()));
		case TITLE:
			String title = Utils.splitCamalCase(Utils.stripPrefix(m.getName()));
			return  title ;
		case DESCRIPTION:
			ValueDescription annotation = m.getAnnotation(ObjectAnnotations.ValueDescription.class);
			if (annotation!= null){
				return annotation.value();
			} 
			
			try {
				Object invoke = m.invoke(superObject, null);
				return "" + (invoke!=null ? invoke.toString() : "not set");
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			
			return "";
			
		case NAME_BY_ANNOTATION :
			//retrieves the Name by the @Default annotation
			Method method = null;
			for (Method m2 : superObject.getClass().getMethods() ){
				if (m2.isAnnotationPresent(ObjectAnnotations.DefaultValue.class)){
					method = m2;
				}
			}
			
			Object invoke = null;
			
			if (method!=null && method.getParameterTypes().length == 0){
				try {
					
					invoke = method.invoke(superObject, null);
				
				
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
			
			if (invoke!=null)
				return invoke.toString();
			else
				return toHumanReadable(m, superObject, TYPE.NAME);
			
		}

		return m.getName();
	}
}
